package com.zjw.zy.componse.unityui.unity;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

/**
 * @author ：zhong.jw
 * @date ：Created in 2023/3/14 12:55
 */
public abstract class BaseUnityContentView extends FrameLayout {

    protected View unityOperatorContainer;

    protected UnityMessageListener mUnityMessageListener;

    public BaseUnityContentView(@NonNull Context context) {
        super(context);
    }

    public BaseUnityContentView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public BaseUnityContentView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public BaseUnityContentView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    public void attachUnityView(@NonNull View unityView, UnityMessageListener listener) {
        unityOperatorContainer = onOperatorContentView();
        LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        this.addView(unityView, params);
        this.addView(unityOperatorContainer, params);

        mUnityMessageListener = listener;
    }

    public void onDetachUnityView() {
        unityOperatorContainer = null;
    }

    /**
     * 与unity底层通信
     */
    public void sendUnityMessage(@NonNull String gameObject, @NonNull String method, @NonNull String args) {
        Log.d(this.getClass().getSimpleName(), "sendUnityMessage : gameObject = [" + gameObject + "], method = [" + method + "], args = [" + args + "]");
        if (mUnityMessageListener != null) {
            mUnityMessageListener.onSendUnityMessage(gameObject, method, args);
        }
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        onBindListener();
    }

    protected abstract void onBindListener();

    protected abstract View onOperatorContentView();

    public interface UnityMessageListener {
        void onSendUnityMessage(String gameObject, String method, String args);
    }
}
